//
//  HomePageHeader.swift
//  ZNZXSuperMarket
//
//  Created by 四川中农 on 2018/7/25.
//  Copyright © 2018年 四川中农. All rights reserved.
//

import UIKit
import LLCycleScrollView

class HomePageHeader: UIView {
    
    var indexModel:IndexModel?
    
    var bannerView : LLCycleScrollView!
    
    var collectionView:UICollectionView!
    
    var secondLabel:UILabel!
    
    var minuteLabel:UILabel!
    
    var hourLabel:UILabel!
    
    var timeLabel:UILabel!
    
    var timer:Timer?
    
    var countDown = 0
    
    var loginedClosure:TouchBlock!
    
    var backSeleGoodsid:BackIntValue!
    
    var bannerBottom:CGFloat = 0
    
    var timeImage:UIImageView!
    
    var backBannerIndex:BackIntValue!

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.nav_color
        self.clipsToBounds = true
        initContent()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    private func initContent(){
        
        bannerView = LLCycleScrollView.llCycleScrollViewWithFrame(CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: UIScreen.ScreenWidth/(375/250)))
        bannerView.delegate = self
        // 设置图片显示方式=UIImageView的ContentMode
        bannerView.imageViewContentMode = .scaleToFill
        // 设置当前PageControl的样式 (.none, .system, .fill, .pill, .snake)
        bannerView.customPageControlStyle = .fill
        bannerView.customPageControlTintColor = UIColor.init(hexColor: "#f7c201")
        bannerView.customPageControlInActiveTintColor = UIColor.init(hexColor: "#ffffff")
        
        // 添加到view
        self.addSubview(bannerView)
        self.bannerBottom = self.bannerView.bottom
        
        // 11 20
        
        var label = Utils.labelWith(frame: CGRect.init(x: 23, y: self.bannerView.bottom + 15, width: 60, height: 14), font: UIFont.boldSystemFont(ofSize: 14), textAlignment: .left, textColor: "#000000", text: "爆品直降")
        self.addSubview(label)
        
        let tagImg = UIImageView.init(image: UIImage.init(named: "btyangshi_1"))
        tagImg.frame = CGRect.init(x: 12, y: 0, width: 11, height: 20)
        tagImg.centerY = label.centerY + 2
        self.addSubview(tagImg)
        
        self.height = tagImg.bottom + 10
        
        self.secondLabel = Utils.labelWith(frame: CGRect.init(x: UIScreen.ScreenWidth - 12 - 15, y: 0, width: 15, height: 15), font: UIFont.systemFont(ofSize: 10), textAlignment: .center, textColor: "#fefefe", text: "00")
        self.secondLabel.backgroundColor = UIColor.init(hexColor: "#da1212")
        self.secondLabel.setCornerRadio(radio: 3, isMask: true)
        self.secondLabel.centerY = label.centerY
        self.addSubview(self.secondLabel)
        
        label = Utils.labelWith(frame: CGRect.init(x: self.secondLabel.left - 5 - 2, y: 0, width: 3, height: 15), font: UIFont.systemFont(ofSize: 15), textAlignment: .center, textColor: "#da1212", text: ":")
        label.centerY = self.secondLabel.centerY - 2
        self.addSubview(label)
        
        self.minuteLabel = Utils.labelWith(frame: CGRect.init(x: label.left - 3 - 15, y: 0, width: 15, height: 15), font: UIFont.systemFont(ofSize: 10), textAlignment: .center, textColor: "#fefefe", text: "00")
        self.minuteLabel.backgroundColor = UIColor.init(hexColor: "#da1212")
        self.minuteLabel.setCornerRadio(radio: 3, isMask: true)
        self.minuteLabel.centerY = self.secondLabel.centerY
        self.addSubview(self.minuteLabel)
        
        label = Utils.labelWith(frame: CGRect.init(x: self.minuteLabel.left - 5 - 2, y: 0, width: 3, height: 15), font: UIFont.systemFont(ofSize: 15), textAlignment: .center, textColor: "#da1212", text: ":")
        label.centerY = self.secondLabel.centerY - 2
        self.addSubview(label)
        
        self.hourLabel = Utils.labelWith(frame: CGRect.init(x: label.left - 3 - 15, y: 0, width: 15, height: 15), font: UIFont.systemFont(ofSize: 10), textAlignment: .center, textColor: "#fefefe", text: "00")
        self.hourLabel.backgroundColor = UIColor.init(hexColor: "#da1212")
        self.hourLabel.setCornerRadio(radio: 3, isMask: true)
        self.hourLabel.centerY = self.secondLabel.centerY
        self.addSubview(self.hourLabel)
        
        let width = "距14点开场剩余".rect(withFont: UIFont.systemFont(ofSize: 10), size: CGSize.init(width: CGFloat.greatestFiniteMagnitude, height: 10)).width + 2

        self.timeLabel = Utils.labelWith(frame: CGRect.init(x: self.hourLabel.left - 10 - width, y: 0, width: width, height: 10), font: UIFont.systemFont(ofSize: 10), textAlignment: .left, textColor: "#333333", text: "距14点开场剩余")
        self.timeLabel.centerY = self.hourLabel.centerY
        self.addSubview(self.timeLabel)

        timeImage = UIImageView.init(image: UIImage.init(named: "time_1"))
        timeImage.frame = CGRect.init(x: self.timeLabel.left - 4 - 10, y: 0, width: 10, height: 10)
        timeImage.centerY = self.hourLabel.centerY
        self.addSubview(timeImage)
        
        self.height = timeImage.bottom + 15
        
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize.init(width: 140, height: 188)
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 2
        layout.sectionInset = UIEdgeInsetsMake(5, 12, 5, 7)
        self.collectionView = UICollectionView.init(frame: CGRect.init(x: 0, y: self.hourLabel.bottom + 8, width: UIScreen.ScreenWidth, height: 195), collectionViewLayout: layout)
        self.collectionView.delegate = self
        self.collectionView.backgroundColor = UIColor.nav_color
        self.collectionView.dataSource = self
        self.collectionView.register(UINib.init(nibName: "ExplosiveGoodsCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "ExplosiveGoodsCollectionViewCell")
        self.collectionView.showsHorizontalScrollIndicator = false
        self.addSubview(self.collectionView)
        
        self.height = self.collectionView.bottom + 17
        
    }
    
    func updateSubViews(WithModel model:IndexModel){
        self.indexModel = model
        var imageUrl =  [String]()
        for bannerModel in model.banners! {
            imageUrl.append(bannerModel.img)
        }
        self.bannerView.imagePaths = imageUrl
        if model.siteGoods?.count == 0 {
            self.height = self.bannerBottom + 8
            return
        }else{
            self.height = self.collectionView.bottom + 17
        }
        
        
        switch model.fireSite?.state {
        case 0:
            var time = "\(model.fireSite?.startTime ?? 0)".timeStampToString(timeFormat: "YYYY-MM-dd HH:mm:ss")
            let startIndex = time.index(time.startIndex, offsetBy: 11)
            let endIndex = time.index(time.startIndex, offsetBy: 13)
            time = String(time[startIndex..<endIndex])
            let detailString = "距\(time)点开场剩余"
            
            self.countDown = Int(((model.fireSite?.startTime)! - (Date().timeIntervalSince1970 * 1000)) / 1000)
            self.timer?.invalidate()
            self.timer = nil
            self.timeLabel.text = detailString
            
            self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerClick), userInfo: nil, repeats: true)
            RunLoop.current.add(self.timer!, forMode: .commonModes)
            
            let width = detailString.rect(withFont: UIFont.systemFont(ofSize: 10), size: CGSize.init(width: CGFloat.greatestFiniteMagnitude, height: 10)).width + 2
            self.timeLabel.left = self.hourLabel.left - 10 - width
            self.timeImage.left = self.timeLabel.left - 4 - 10
        case 1:
            // 本场结束
            let detailString = "距本场结束剩余"
            self.countDown = Int(((model.fireSite?.endTime)! - (Date().timeIntervalSince1970 * 1000)) / 1000)
            self.timer?.invalidate()
            self.timer = nil
            self.timeLabel.text = detailString
            self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerClick), userInfo: nil, repeats: true)
            RunLoop.current.add(self.timer!, forMode: .commonModes)
            
            let width = detailString.rect(withFont: UIFont.systemFont(ofSize: 10), size: CGSize.init(width: CGFloat.greatestFiniteMagnitude, height: 10)).width + 2
            self.timeLabel.left = self.hourLabel.left - 10 - width
            self.timeImage.left = self.timeLabel.left - 4 - 10
        case 2:
            self.timer?.invalidate()
            self.timer = nil
            self.timeLabel.text = "已结束"
            self.hourLabel.text = "00"
            self.minuteLabel.text = "00"
            self.secondLabel.text = "00"
            
            let width = "已结束".rect(withFont: UIFont.systemFont(ofSize: 10), size: CGSize.init(width: CGFloat.greatestFiniteMagnitude, height: 10)).width + 2
            self.timeLabel.left = self.hourLabel.left - 10 - width
            self.timeImage.left = self.timeLabel.left - 4 - 10
        default:
            break
        }
        
        self.collectionView.reloadData()
    }

    @objc func timerClick(){
    
        if self.countDown > 0 {
            
            let result = Utils.getMMSSFromSS(count: self.countDown)
            self.hourLabel.text = result.0
            self.minuteLabel.text = result.1
            self.secondLabel.text = result.2
            countDown = countDown - 1
        }else{
            self.timer?.invalidate()
            self.timer = nil
        }
    }
    
}

extension HomePageHeader : UICollectionViewDelegate,UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.indexModel?.siteGoods == nil ? 0 : self.indexModel!.siteGoods!.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ExplosiveGoodsCollectionViewCell", for: indexPath) as! ExplosiveGoodsCollectionViewCell
        cell.reload(withModel: (self.indexModel?.siteGoods![indexPath.row])!)
        cell.loginClosure = { [weak self] in
            self?.loginedClosure()
        }
        cell.backGoodsId = {(goodsID) in
            
            if self.indexModel?.fireSite?.state == 2 {
                PKhud.showText(text: "活动已结束~")
                return
            }
            if self.indexModel?.fireSite?.state == 0 {
                PKhud.showText(text: "活动未开始~")
                return
            }
            
            Utils.insertCart(goodsId: goodsID) { (value) in
                if value.0 {
                    PKhud.showText(text: "添加成功~")
                }else{
                    PKhud.showText(text: value.1)
                }
            }
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if self.indexModel?.fireSite?.state == 2 {
            PKhud.showText(text: "活动已结束~")
            return
        }
        if self.indexModel?.fireSite?.state == 0 {
            PKhud.showText(text: "活动未开始~")
            return
        }
        if self.backSeleGoodsid != nil {
            self.backSeleGoodsid((self.indexModel?.siteGoods![indexPath.row].id)!)
        }
    }
}


extension HomePageHeader : LLCycleScrollViewDelegate {
    func cycleScrollView(_ cycleScrollView: LLCycleScrollView, didSelectItemIndex index: NSInteger) {
        if self.backBannerIndex != nil {
            self.backBannerIndex(index)
        }
    }
}

















